/**   
 * @Title: BaseAction.java 
 * CopyRight(c)2010-DMX 
 */
package com.dmx.fw.web.struts2.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dmx.fw.security.bean.Operator;
import com.dmx.fw.constant.ViewConstant;
import com.dmx.fw.exception.GeneralException;
import com.dmx.fw.exception.GeneralExceptionHandler;
import com.dmx.fw.util.StrUtils;
import com.dmx.fw.web.util.Helper;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/** 
 * @Description: Action基类
 * @author: system
 * @date: 2006
 * @version V1.0 
 * 
 */
public class BaseAction extends ActionSupport {
	
	protected Log log=LogFactory.getLog(this.getClass());
	/** 
	 * @Fields GLOBAL_ERROR_INFO_KEY：session中错误信息属性的key
	 */ 
	protected static final String GLOBAL_ERROR_INFO_KEY = ViewConstant.GLOBAL_ERROR_INFO_KEY;

	/** 
	 * @Fields GLOBAL_SUCCESS_INFO_KEY: session中成功信息属性的key
	 */
	protected static final String GLOBAL_SUCCESS_INFO_KEY = ViewConstant.GLOBAL_SUCCESS_INFO_KEY;

	/** 
	 * @Fields ACTION_SUCCESS_URL: session中存放action成功需要转发的url
	 */
	protected static final String ACTION_SUCCESS_URL = ViewConstant.ACTION_SUCCESS_URL;

	 /** 
	  * @Fields pageState：default pageState value
	  */ 
	protected String pageState = ViewConstant.ADDSTATUS;

	/** 
	 * @Fields act：the act of accessing action
	 */ 
	protected String act = ViewConstant.ADDINPUT;
	
	/** 
	 * @Fields validateMsgList：校验信息列表
	 */
	protected List validateMsgList;

	public String execute() throws Exception {
		try{
			//校验
			if (ViewConstant.ADDSUBMIT.equals(act)) {
				doValidateAddSubmit();
			} else if (ViewConstant.EDITSUBMIT.equals(act)) {
				doValidateEditSubmit();
			} else if (ViewConstant.DELETE.equals(act)) {
				doValidateDelete();
			} else if (ViewConstant.OTHERTATUS.equals(act)) {
				doValidateOther();
			}else{
				  Method method = null;
			      try {
			          method = this.getClass().getMethod("doValidate"+act, null);
			          if(method!=null)
			             return (String) method.invoke(this, null);
			      } catch (Exception e) {
			    	  if(!(e instanceof NoSuchMethodException)){
			    		  throw e;
			    	  }
			    	  //System.out.println("action执行该('" + act + "')方法时出错：");
			    	  //e.printStackTrace();
			    	 
			      }
			}
			String validMsg = validMsgListHandler(validateMsgList);
			if(validMsg != null){   //校验失败，返回校验信息
				this.setAjaxJsonMsgResult(validMsg,null);
				return null;
			}
			
			
			
			if (ViewConstant.ADDINPUT.equals(act)) {
				this.pageState = ViewConstant.ADDSTATUS;
				return doAddInput();
			} else if (ViewConstant.ADDSUBMIT.equals(act)) {
				return doAddSubmit();
			} else if (ViewConstant.EDITINPUT.equals(act)) {
				this.pageState = ViewConstant.EDITSTATUS;
				return doEditInput();
			} else if (ViewConstant.EDITSUBMIT.equals(act)) {
				return doEditSubmit();
			} else if (ViewConstant.DELETE.equals(act)) {
				return doDelete();
			} else if (ViewConstant.VIEW.equals(act)) {
				this.pageState = ViewConstant.VIEWSTATUS;
				return doView();
			}else if (ViewConstant.QUERY.equals(act)) {
				this.pageState = ViewConstant.ADDSTATUS;
				return doQuery();
			}else if (ViewConstant.OTHERTATUS.equals(act)) {
				return doOther();
			}else{
				  Method method = null;
			      try {
			          method = this.getClass().getMethod(act, null);
			          if(method!=null)
			             return (String) method.invoke(this, null);
			      } catch (Exception e) {
			    	  //System.out.println("action执行该('" + act + "')方法时出错：");
			    	  //e.printStackTrace();
			    	  throw e;
			      }
			}
		    return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			GeneralException ge = GeneralExceptionHandler.Handle(e);
			String retMsg = getText(ge.getMessage());
			String msgDetail = ge.getErrorDescription();
			this.setErrorInfo(retMsg);
			if( retMsg != null && !retMsg.equals("")){
				//this.setAjaxJsonMsgResult(retMsg,msgDetail);
			}else{
				if (ViewConstant.DELETE.equals(act)){
					//this.setAjaxJsonMsgResult(getText("message.DeleteError"),msgDetail);
				}else{
					//this.setAjaxJsonMsgResult(getText("message.Error"),msgDetail);
				}
			}
			return ERROR;
		}
	}

	/**
	 * 进入添加输入界面
	 */
	public String doAddInput() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 执行添加提交操作
	 */ 
	public String doAddSubmit() throws Exception {
		return SUCCESS;
	}

	/**
	 * 进入修改输入界面
	 */ 
	public String doEditInput() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 执行修改提交界面
	 */
	public String doEditSubmit() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 执行删除操作
	 */
	public String doDelete() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 执行查看动作
	 */
	public String doView() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 进入查询页面界面
	 */	
	public String doQuery() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 进入其它页面界面
	 */	
	public String doOther() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 验证是否为唯一性
	 * @throws Exception
	 * @see {@link Helper#isUniqueCheck(String, String, boolean)}
	 */
	public String uniqueCheck()throws Exception {
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		String key=request.getParameter("key");
		String codeName=request.getParameter("codeName");
		String isEdit=request.getParameter("isEdit");
		response.reset();
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter writer=response.getWriter();
		writer.print(Helper.isUniqueCheck(key, codeName, StringUtils.isBlank(codeName)?false:Boolean.parseBoolean(isEdit)));
		writer.close();
		response.flushBuffer();
        return null;
	}

	/**
	 * 保存错误信息
	 * 
	 * @param session
	 * @param errorMsg
	 */
	protected void setErrorInfo(String errorMsg) {
		if (errorMsg == null)
			return;
		
		errorMsg = StrUtils.escapeHTMLTags(errorMsg);
		Map session = ActionContext.getContext().getSession();
		List errorMsgList = (List) session.get(GLOBAL_ERROR_INFO_KEY);

		session.remove(GLOBAL_SUCCESS_INFO_KEY);

		if (errorMsgList == null) {
			errorMsgList = new ArrayList();
		}
		for (int i = 0; i < errorMsgList.size(); i++) {
			if (errorMsg.equals((String) errorMsgList.get(i))) {
				return;
			}
		}
		errorMsgList.add(errorMsg);
		session.put(GLOBAL_ERROR_INFO_KEY, errorMsgList);
	}

	/**
	 * 设置成功信息，在页面上方进行展示
	 */
	protected void setSuccessinfo(String successMsg) {

		if (successMsg == null)
			return;
		
		successMsg = StrUtils.escapeHTMLTags(successMsg);
		Map session = ActionContext.getContext().getSession();
		List successMsgList = (List) session.get(GLOBAL_SUCCESS_INFO_KEY);

		session.remove(GLOBAL_ERROR_INFO_KEY);

		if (successMsgList == null) {
			successMsgList = new ArrayList();
		}
		for (int i = 0; i < successMsgList.size(); i++) {
			if (successMsg.equals((String) successMsgList.get(i))) {
				return;
			}
		}
		successMsgList.add(successMsg);
		session.put(GLOBAL_SUCCESS_INFO_KEY, successMsgList);
	}



	/**
	 * logout，或login之前清除session
	 * 
	 */
	protected void clearSession() {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		session.remove(ViewConstant.OPERATOR_SESSION_KEY);
		session.remove(ViewConstant.COMMONQUERY_CONDITION_SESSION_NAME);
		session.remove(ViewConstant.USER_PERMISSION_SESSION);
		session.remove(ViewConstant.DISABLEMENUINFO);
		session.remove(ViewConstant.GLOBAL_ERROR_INFO_KEY);
		session.remove(ViewConstant.GLOBAL_SUCCESS_INFO_KEY);
		session.remove(ViewConstant.RE_LOCATION_URL_KEY);
		session.remove(ViewConstant.ACTION_SUCCESS_URL);
		session.remove(ViewConstant.GLOBAL_DETAIL_ERROR_INFO_KEY);
	}

	/**
	 * 取得当前操作员
	 * 
	 * @return Operator
	 */
	protected Operator getCurrOperator() {
		ActionContext ctx = ActionContext.getContext();
		Operator currOptr = (Operator) ctx.getSession().get(
				ViewConstant.OPERATOR_SESSION_KEY);
		return currOptr;
	}
	
	/**
	 * @Description 设置ajax结果,将结果字符串写到response流中
	 * @param retString: 结果字符串
	 * @throws IOException
	 */
	protected void setAjaxResult(String retString) throws IOException{
		if(retString != null){
			ServletActionContext.getResponse().setContentType("charset=UTF-8");
			ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
			ServletActionContext.getResponse().getWriter().write(retString);
			
		}
	}
	
	/**
	 * @Description 将页面回调的url拼成json格式返回前台
	 * @param resultUrl: 返回页面时，页面回调的url的字符串
	 * @throws IOException
	 */
	protected void setAjaxJsonUrlResult(String resultUrl) throws IOException{
		StringBuffer retString = new StringBuffer();
		retString.append("{");
		retString.append("\"url\":\""+resultUrl+"\"");
		retString.append("}");
		setAjaxResult(retString.toString());
	}
	
	/**
	 * @Description 将信息内容拼成json格式返回给前台
	 * @param resultMsg: 结果信息内容
	 * @param msgDetail: 结果信息详细内容
	 * @throws IOException
	 */
	protected void setAjaxJsonMsgResult(String resultMsg,String msgDetail) throws IOException{
		StringBuffer retString = new StringBuffer();
		retString.append("{");
		retString.append("\"message\":\""+resultMsg+"\"");
		/*retString.append(",\"description\":\"");
		if(msgDetail != null){
			retString.append(msgDetail);
		}
		retString.append("\"");*/
		retString.append("}");
		setAjaxResult(retString.toString());
	}
	
	/**
	 * @Description 将信息内容拼成json格式返回给前台
	 * @param resultMsg:
	 * @param msgDetail:  预留参数
	 * @throws IOException
	 */
	protected void setAjaxJsonMsgResult(String resultMsg) throws IOException{
		StringBuffer retString = new StringBuffer();
		retString.append("{");
		retString.append("\"message\":\""+resultMsg+"\"");
		retString.append("}");
		setAjaxResult(retString.toString());
	}
	
	/*
	 * 进行校验
	 */
	protected void doValidateAddSubmit(){
		
	}
	protected void doValidateEditSubmit(){
		
	}
	protected void doValidateDelete(){
		
	}
	protected void doValidateOther(){
		
	}
	
	/**
	 * @Description 增加校验信息
	 * @param failedMsg: 源
	 */
	protected void addValidateFailedMsg(String failedMsg){
		if(validateMsgList == null){
			validateMsgList = new ArrayList();
		}
		validateMsgList.add(failedMsg);
	}
	
	/**
	 * @Description 校验信息列表结果处理
	 * @param msgList
	 * @return String
	 */
	private String validMsgListHandler(List<String> msgList){
		if(msgList != null && msgList.size()>0){
			StringBuffer retMsg = new StringBuffer();
			for(String msg:msgList){      
				retMsg.append(msg);
			}
			return retMsg.toString();
		}else{
			return null;
		}
	}

	public String getPageState() {
		return pageState;
	}

	public void setPageState(String pageState) {
		this.pageState = pageState;
	}

	public String getAct() {
		return act;
	}

	public void setAct(String act) {
		this.act = act;
	}
}
